<template>
  <PageContainer>
    <AsyncState
      :loading="postLoading"
      :error="postError"
      :isEmpty="!post"
      emptyMessage="未找到对应的帖子"
      :retry="loadPost"
    >
      <article class="post-card">
        <header class="post-header">
          <div>
            <h1 class="post-title">{{ post.title }}</h1>
            <div class="post-meta">
              <span class="meta-item">
                发布于 {{ formatDate(post.created_at) }}
              </span>
              <span class="meta-item">作者：{{ post.author || '匿名用户' }}</span>
              <span v-if="post.likes !== undefined" class="meta-item">
                点赞 {{ post.likes }}
              </span>
            </div>
          </div>
          <RouterLink class="back-link" to="/forum">返回讨论区</RouterLink>
        </header>
        <div class="tag-group" v-if="post.tags?.length">
          <span v-for="tag in post.tags" :key="tag" class="tag">#{{ tag }}</span>
        </div>
        <p class="post-content">
          {{ post.content }}
        </p>
      </article>

      <CommentList
        v-if="replyItems.length"
        title="帖子回复"
        :items="replyItems"
        :count="replyItems.length"
      />
    </AsyncState>

    <section class="interaction-grid">
      <div class="comment-column">
        <CommentEditor
          v-model="commentText"
          :loading="commentSubmitting"
          :showLoginPrompt="!isAuthenticated"
          @submit="handleSubmitComment"
          @login="focusLogin"
        >
          <template #title>
            <div class="editor-title-bar">
              <h3>评论区</h3>
              <span v-if="user" class="current-user">
                当前用户：{{ user.username }}
                <button type="button" class="logout-link" @click="logout">
                  退出
                </button>
              </span>
            </div>
          </template>
        </CommentEditor>
        <p v-if="commentError" class="error-text">{{ commentError }}</p>
        <p v-if="commentSuccess" class="success-text">{{ commentSuccess }}</p>
      </div>

      <aside class="auth-column">
        <div class="auth-card">
          <h3 class="auth-title">账号登录</h3>
          <p class="auth-subtitle">
            登录后可参与评论交流，默认示例账号：admin / admin123
          </p>
          <form class="auth-form" @submit.prevent="handleLogin">
            <label class="form-item">
              <span>用户名</span>
              <input
                v-model="loginForm.username"
                type="text"
                autocomplete="username"
                placeholder="请输入用户名"
                required
              />
            </label>
            <label class="form-item">
              <span>密码</span>
              <input
                v-model="loginForm.password"
                type="password"
                autocomplete="current-password"
                placeholder="请输入密码"
                required
              />
            </label>
            <button type="submit" class="login-submit" :disabled="authLoading">
              {{ authLoading ? '登录中...' : '立即登录' }}
            </button>
            <p v-if="authError" class="error-text">{{ authError }}</p>
            <p v-if="loginTip" class="success-text">{{ loginTip }}</p>
          </form>
        </div>
        <div class="post-stats" v-if="post">
          <h4>帖子数据</h4>
          <ul>
            <li><strong>创建时间：</strong>{{ formatDate(post.created_at) }}</li>
            <li><strong>回复数量：</strong>{{ replyItems.length }}</li>
            <li><strong>评论数量：</strong>{{ commentItems.length }}</li>
          </ul>
        </div>
      </aside>
    </section>

    <CommentList
      title="用户评论"
      :items="commentItems"
      :count="commentItems.length"
      emptyMessage="来发表第一条评论吧～"
    />
    <p v-if="commentRequestError" class="error-text">
      评论加载失败：{{ commentRequestError }}
    </p>
  </PageContainer>
</template>

<script setup>
import { computed, reactive, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import PageContainer from '../components/PageContainer.vue'
import AsyncState from '../components/AsyncState.vue'
import CommentList from '../components/CommentList.vue'
import CommentEditor from '../components/CommentEditor.vue'
import {
  createComment,
  getComments,
  getPostDetail,
} from '../api/client'
import { useAsyncData } from '../composables/useAsyncData'
import { useAuth } from '../composables/useAuth'
import { formatDate } from '../utils/formatters'

const route = useRoute()
const postId = computed(() => Number(route.params.id))

const {
  data: post,
  loading: postLoading,
  error: postError,
  execute: fetchPost,
} = useAsyncData((id) => getPostDetail(id), {
  initialValue: null,
})

const {
  data: comments,
  loading: commentLoading,
  error: commentRequestError,
  execute: fetchComments,
} = useAsyncData((id) =>
  getComments({
    target_type: 'post',
    target_id: id,
  }), {
  initialValue: [],
  transform: (response) => response?.items ?? [],
})

const { user, login, logout, isAuthenticated, error: authError, loading: authLoading } = useAuth()

const commentText = ref('')
const commentSubmitting = ref(false)
const commentError = ref('')
const commentSuccess = ref('')
const loginTip = ref('')

const loginForm = reactive({
  username: '',
  password: '',
})

function loadPost() {
  if (!postId.value) return Promise.resolve()
  return fetchPost(postId.value)
}

function loadComments() {
  if (!postId.value) return Promise.resolve()
  return fetchComments(postId.value)
}

watch(
  () => postId.value,
  () => {
    loadPost()
    loadComments()
  },
  { immediate: true },
)

const replyItems = computed(() => {
  if (!post.value?.replies?.length) return []
  return post.value.replies.map((reply) => {
    const author = reply.author || '匿名用户'
    return {
      id: reply.id,
      author,
      initial: author.slice(0, 1).toUpperCase(),
      createdAt: formatDate(reply.created_at || post.value.created_at),
      content: reply.content,
      badge: author === post.value.author ? '作者回复' : undefined,
    }
  })
})

const commentItems = computed(() =>
  comments.value.map((item) => {
    const authorName = item.author?.username || '匿名用户'
    return {
      id: item.id,
      author: authorName,
      initial: authorName.slice(0, 1).toUpperCase(),
      avatar: item.author?.avatar,
      createdAt: formatDate(item.created_at),
      content: item.content,
    }
  }),
)

async function handleLogin() {
  loginTip.value = ''
  try {
    await login({
      username: loginForm.username.trim(),
      password: loginForm.password,
    })
    loginTip.value = '登录成功，欢迎参与讨论！'
    commentError.value = ''
  } catch (error) {
    loginTip.value = ''
    if (error?.message) {
      commentError.value = error.message
    }
  }
}

function focusLogin() {
  loginTip.value = '请先登录再发表评论'
}

async function handleSubmitComment() {
  const content = commentText.value.trim()
  if (!content) {
    commentError.value = '评论内容不能为空'
    return
  }
  if (!isAuthenticated.value) {
    focusLogin()
    return
  }
  commentSubmitting.value = true
  commentError.value = ''
  commentSuccess.value = ''
  try {
    await createComment({
      target_type: 'post',
      target_id: postId.value,
      content,
    })
    commentText.value = ''
    commentSuccess.value = '评论发布成功'
    await loadComments()
  } catch (error) {
    if (error.body?.sensitive_terms?.length) {
      commentError.value = `内容审核未通过，敏感词：${error.body.sensitive_terms.join('、')}`
    } else {
      commentError.value = error.message || '评论发布失败，请稍后重试'
    }
  } finally {
    commentSubmitting.value = false
  }
}
</script>

<style scoped>
.post-card {
  display: flex;
  flex-direction: column;
  gap: 16px;
  border: 1px solid #ebeef5;
  border-radius: 12px;
  padding: 24px;
  background: #fff;
}

.post-header {
  display: flex;
  justify-content: space-between;
  gap: 16px;
  align-items: flex-start;
}

.post-title {
  margin: 0;
  font-size: 26px;
  font-weight: 700;
  line-height: 1.3;
}

.post-meta {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  margin-top: 12px;
  color: #909399;
  font-size: 14px;
}

.meta-item {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.back-link {
  color: #409eff;
  text-decoration: none;
  font-size: 14px;
}

.back-link:hover {
  text-decoration: underline;
}

.tag-group {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag {
  padding: 4px 10px;
  border-radius: 999px;
  background: #ecf5ff;
  color: #409eff;
  font-size: 12px;
}

.post-content {
  margin: 0;
  line-height: 1.8;
  color: #303133;
  white-space: pre-wrap;
}

.interaction-grid {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 24px;
}

.comment-column {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.auth-column {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.auth-card {
  border: 1px solid #ebeef5;
  border-radius: 12px;
  padding: 20px;
  background: #fff;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.auth-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.auth-subtitle {
  margin: 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
}

.auth-form {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 6px;
  font-size: 14px;
  color: #606266;
}

.form-item input {
  padding: 10px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  font-size: 14px;
}

.form-item input:focus {
  border-color: #409eff;
  outline: none;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.15);
}

.login-submit {
  padding: 10px 16px;
  border-radius: 8px;
  border: none;
  background: #409eff;
  color: #fff;
  font-size: 14px;
  cursor: pointer;
}

.login-submit:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.post-stats {
  border: 1px solid #ebeef5;
  border-radius: 12px;
  padding: 20px;
  background: #fff;
}

.post-stats h4 {
  margin: 0 0 12px;
  font-size: 16px;
}

.post-stats ul {
  margin: 0;
  padding-left: 18px;
  color: #606266;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.editor-title-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
}

.editor-title-bar h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.current-user {
  font-size: 13px;
  color: #909399;
}

.logout-link {
  margin-left: 8px;
  padding: 2px 8px;
  border-radius: 999px;
  border: 1px solid rgba(64, 158, 255, 0.3);
  background: transparent;
  color: #409eff;
  cursor: pointer;
  font-size: 12px;
}

.error-text {
  margin: 0;
  color: #f56c6c;
  font-size: 13px;
}

.success-text {
  margin: 0;
  color: #67c23a;
  font-size: 13px;
}

@media (max-width: 960px) {
  .interaction-grid {
    grid-template-columns: 1fr;
  }

  .auth-column {
    order: -1;
  }
}
</style>